<?php
/**
 * Common functions (can be referenced by all modules)
 **/


/**
 * Filter functions 
 **/

// {{{ Movie Section
/**
 * Filter out expected query keywords and format them
 *
 * @param  string query keywords
 * @return string formatted query string of keywords
 * @author lythesia
 **/
function filter_query_str($data) {
  // logic or with '|' separate
  if(strpos($data, '|') !== false) {
    return preg_replace('/\s*\|\s*/', ' ', $data);
  }
  // logic and with ' ' separate
  else {
    return '+'.preg_replace('/\s+/', ' +', $data);
  }
}


/**
 * Check keywords length in query string
 *
 * @param  string query keywords
 * @return mixed original string or `false` if each keyword too short
 * @author lythesia
 **/
function check_query_len($data) {
  // try to split into keywords array
  if(strpos($data, '+')) {
    $data = str_replace('+', '', $data);
  }
  foreach(explode(' ', $data) as $val) {
    if(mb_strlen($val) > 3) return true;
  }
  return false;
}


/**
 * Filter out Api returned format
 *
 * @param  string format
 * @return mixed `json` on default or `false` when neither `json` or `xml`
 * @author lythesia
 **/
function filter_api_format($data) {
  if($data === '') return 'json';
  if($data !== 'json' and $data !== 'xml') return false;
  return $data;
}


/**
 * Filter out Movie ID
 *
 * @param  string movie_id
 * @return mixed original id string or `false` if not a valid `movie_id`
 * @author lythesia
 **/
function filter_movieid($data) {
  return preg_match('/^v\d{7}$/', $data) ? $data : false;
}


/**
 * Filter out Movie allowed fields
 *
 * @param  string movie fields(with ',' separate)
 * @return mixed original fields string or `false` if contains invalid field
 * @author lythesia
 **/
function filter_movie_field($data) {
  static $field = ['id', 'title', 'aka', 'summary', 'producedby', 'budget', 'releasedate', 'filmlocation', 'country', 'runtime', 'genre', 'language', 'rating', 'ratingnum', 'mpaa', 'poster'];
  foreach(explode(',', $data) as $f) {
    if(!in_array($f, $field)) {
      return false;
    }
  }
  return $data;
}


/**
 * Filter out Movie allowed relations
 *
 * @param  string movie relations(with ',' separate)
 * @return mixed original relations string or `false` if contains invalid relation
 * @author lythesia
 **/
function filter_movie_rel($data) {
  static $rels= ['genres', 'persons', 'director', 'actors', 'crew'];
  foreach(explode(',', $data) as $r) {
    if(!in_array($r, $rels)) {
      return false;
    }
  }
  return $data;
}


/**
 * Filter out Movie allowed mpaa
 *
 * @param  array movie mpaa(combinded as logic or)
 * @return mixed original mpaa array or `false` if contains invalid mpaa
 * @author lythesia
 **/
function filter_movie_mpaa($data) {
  static $mpaas = ['R', 'r', 'PG', 'pg', 'PG-13', 'PG13', 'pg-13', 'pg13', 'NC-17', 'NC17', 'nc-17', 'nc17', 'G', 'g'];
  foreach($data as $m) {
    if(!in_array($m, $mpaas)) {
      return false;
    }
  }
  return $data;
}
// }}} end Movie Section


// {{{ Person Section
/**
 * Filter out Person ID
 *
 * @param  string person_id
 * @return mixed original id or `false` if not a valid `person_id`
 * @author lythesia
 **/
function filter_personid($data) {
  return preg_match('/^p\d{7}$/', $data) ? $data : false;
}


/**
 * Filter out Person allowed fields
 *
 * @param  string person fields(with ',' separate)
 * @return mixed original fileds or `false` if contains invalid field
 * @author lythesia
 **/
function filter_person_field($data) {
  static $field = ['id', 'name', 'aka', 'birthdate', 'deathdate', 'gender', 'occupation', 'resume', 'poster'];
  foreach(explode(',', $data) as $f) {
    if(!in_array($f, $field)) {
      return false;
    }
  }
  return $data;
}


/**
 * Filter out Person allowed relations
 *
 * @param  string person relations(with ',' separate)
 * @return mixed original relations or `false` if contains invalid relation
 * @author lythesia
 **/
function filter_person_rel($data) {
  static $rels= ['genres', 'movies', 'castmovies', 'crewmovies'];
  foreach(explode(',', $data) as $r) {
    if(!in_array($r, $rels)) {
      return false;
    }
  }
  return $data;
}
/// }}} end Person Section


/// {{{ Common Section
/**
 * Filter out date
 *
 * @param  string date
 * @return mixed  array(`YYYY`, `MM`, `DD`) or false if not match the format
 * @author lythesia
 **/
function filter_date($data) {
  $ymd = array();
  // more tolerate regex
  //if(preg_match_all('/^(?<year>[0-9]{4})(-(?<mon>0[1-9]|1[0-2])(-(?<day>0[1-9]|[1-2][0-9]|3[0-1]))?)?$/', $data, $ymd)) {
  if(preg_match('/^(?<year>\d{4})-(?<mon>\d{2})-(?<day>\d{2})$/', $data, $ymd)) {
    return $ymd;
  }
  return false;
}
/// }} end Common Section


/**
 * Parse complex query condition into sql format
 *
 * @param  array query condition
 * @return array foramtted query conditon array
 * @author lythesia
 **/
function parse_complex_cond($cond) {
  $map = array();

  foreach($cond as $_key => $_val) {
    if(!empty($_val)) {
      switch($_key) {
      // convert to fulltext search format
      case 'title': case 'name': case 'aka': case 'genre':
      case 'title,aka': case 'name,aka':
        $map['_string'][] = 'MATCH ('.$_key.') AGAINST ("'.$_val.'" IN BOOLEAN MODE)';
        break;
      default:
        $map[$_key] = $_val;
        break;
      }
    }
  }
  if(!empty($map['_string']))
    $map['_string'] = implode(' AND ', $map['_string']);
  return $map;
}
